// pages/geren/geren.js

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: "", //用户信息
    usedPoints: 0, //累计消耗积分
    userScore: 0, //用户积分数
    diamondNum: 0, //钻石数
    userBalance: 0, //账户余额
    isApply: 0, // 0 没资格 1 未申请  2 申请中
    vipNum: 0,
    applyNum: 5, //邀请多少人有申请成为推广员的资格
    levelTotal: 0,
    percentage: 0,

    vipImg: '/img/geren/vip1.png'

  },


  toPage(e) {
    var flag = e.currentTarget.dataset.flag;
    if (flag == 'notice') {
      wx.navigateTo({
        url: '/userPackage/pages/notice/notice',
      })
    } else if (flag == 'vip') {
      // 跳转到VIP中心
      wx.navigateTo({
        url: '/mainPackage/pages/vipCenter/vipCenter',
      })

    } else if (flag == 'apply') {

      if (this.data.isApply == 0) {
        wx.navigateTo({
          url: '/userPackage/pages/myUserList/myUserList',
        })
      } else if (this.data.isApply == 1) {
        // 发起成为推广员的申请
        this.applyHandle()
      } else if (this.data.isApply == 2) {
        wx.showToast({
          title: '您的申请正在审核中',
          icon: 'none'
        })
      }
    } else if (flag == 'myDeatil') {
      // 跳转到余额钻石等记录
      var str = e.currentTarget.dataset.str;
      console.log(str);
      wx.navigateTo({
        url: '/userPackage/pages/asset/asset?nav=' + str,
      })
    } else if (flag == 'order') {
      // 订单
      var index = e.currentTarget.dataset.index;
      console.log(index);
      // return
      wx.navigateTo({
        url: '/userPackage/pages/order/order?index=' + index,
      })
    } else if (flag == 'returnList') {
      wx.navigateTo({
        url: '/orderPackage/pages/returnList/returnList',
      })
    } else if (flag == 'userInfo') {
      // 用户信息
      wx.navigateTo({
        url: '/userPackage/pages/userInfo/userInfo',
      })
    } else if (flag == 'address') {
      // 用户地址
      wx.navigateTo({
        url: '/userPackage/pages/address/address',
      })
    } else if (flag == 'collection') {
      // 收藏列表
      wx.navigateTo({
        url: '/userPackage/pages/collect/collect',
      })
    } else if (flag == 'healthRecord') {
      // 健康档案
      wx.navigateTo({
        url: '/userPackage/pages/healthRecords/healthRecords?userId=' + app.globalData.userId,
      })
    } else if (flag == 'detail') {
      // 商品详情
      var id = e.currentTarget.dataset.id;
      wx.redirectTo({
        url: '/mainPackage/pages/productDetail/productDetail?id=' + id,
      })
    } else if (flag == 'code') {
      wx.navigateTo({
        url: '/userPackage/pages/myUserList/myUserList',
      })
    } else if (flag == 'commission') {
      wx.navigateTo({
        url: '/userPackage/pages/commission/commission',
      })
    }
  },

  // 申请成为推广员
  applyHandle() {
    wx.showLoading({
      title: '',
    })
    var url = app.globalData.url + "scUser/addApply",
      that = this;
    app.wxRequest(url, {
        userId: app.globalData.userId,
        companyId: app.globalData.companyId
      }, res => {
        console.log(res);
        if (res.flag) {
          wx.showToast({
            title: '已提交申请，请耐心等待',
            icon: 'none'
          })
          that.setData({
            isApply: 2
          })

          wx.setStorageSync('isApply', 2)

          wx.hideLoading()
        }
      },
      err => {
        console.log(err);
      })


  },

  getMyData() {
    wx.showLoading({
      title: '',
    })
    var url = app.globalData.url + "scUser/listMemberNum",
      applyNum = this.data.applyNum,
      isApply = this.data.isApply,
      that = this;

    app.wxRequest(url, {
        userId: app.globalData.userId,
      }, res => {
        console.log(res);
        if (res.flag) {
          var datas = res.data;
          console.log(datas);
          isApply = isApply == 2 ? 2 : datas >= applyNum ? 1 : 0
          wx.hideLoading()
          that.setData({
            vipNum: datas,
            isApply
          })
          console.log(that.data);
        }
      },
      err => {
        console.log(err);
      })
  },


  getVip(level) {
    console.log(level);
    var url = app.globalData.url + "scVip/getVipLevelList",
      that = this;
    wx.showLoading({
      title: '',
    })
    app.wxRequest(url, {
        companyId: app.globalData.companyId
      }, res => {
        console.log(res);
        if (res.flag) {
          res.data.forEach(item => {
            if (item.vipLevelNumber == level) {

              var levelTotal = item.nextScore,
                percentage = 0,
                usedPoints = app.globalData.usedPoints;

              percentage = (Number(usedPoints) / Number(levelTotal)) * 100
              that.setData({
                levelTotal,
                percentage,
                usedPoints
              })

              wx.setStorageSync('nextLevelScore', item.nextScore)
            }
          })
          wx.hideLoading()
        }
      },
      err => {
        console.log(err);
      })

  },




  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (!wx.getStorageSync('isApply')) {
      this.setData({
        isApply: wx.getStorageSync('isApply')
      })
    }
    this.getMyData() //获取我邀请的人
    wx.stopPullDownRefresh()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var vipImg = '/img/geren/vip' + app.globalData.user.vipLevel + '.png',
      percentage = 0;
    this.setData({
      userScore: app.globalData.userScore,
      userBalance: app.globalData.userBalance,
      diamondNum: app.globalData.diamondNum,
      usedPoints: app.globalData.usedPoints,
      user: app.globalData.user,
      vipImg
    })
    console.log(this.data);
    console.log(levelTotal);
    var levelNum = JSON.parse(wx.getStorageSync('nextLevelScore')),
      levelTotal = 0;
    console.log(levelTotal);
    try {
      if (this.data.user.vipLevel < levelNum[levelNum.length - 1].vipLevelNumber) {
        levelNum.forEach(item => {
          if (this.data.user.vipLevel < item.vipLevelNumber && this.data.user.usedPoints < item.nextScore) {
            levelTotal = item.nextScore;
            throw BreakException;
          }
        })
      } else {
        levelTotal = levelNum[levelNum.length - 1].nextScore;
      }
    } catch (error) {
      // console.log(error);
    }


    console.log(levelTotal);
    percentage = (Number(this.data.user.usedPoints) / Number(levelTotal)) * 100;
    if (percentage >= 100) {
      percentage = 100;
    }
    this.setData({
      levelTotal,
      percentage
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.onLoad()
    this.onShow()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})